<template>
	<view class="tackpic" @touchmove.stop.prevent="() => {}">
		<view class="font-title">

			<view :style="{
					transform: `translate(${moveX}px, ${moveY}px)`,
					width: diyWidth+'rpx',
				}" @touchstart="start" @touchend="end" @touchmove="move">
				<image :src="coverImageUrl" class="viewref" mode="widthFix" style="width: 100%;height: 100%">
			</view>

			</image>
		</view>

		<camera v-if="!bgImage" device-position="back" flash="off" @error="cameraError"
			style="width: 100%;height: 100%"></camera>
		<image v-else :src="bgImage" style="width: 100vw;height: 100vh;"></image>
		<view class="pic-bot">
			<view class="left"  @click.stop="takePhoto">
				<u-icon v-if="!bgImage" name="camera" color="#fff" size="50"></u-icon>
				<u-icon v-else name="download" color="#fff" size="50"></u-icon>
			</view>
			<view class="slidercenter">
				<u-slider  @changing="moveing" v-model="value"  activeColor="#ff9900" inactiveColor="#ff9900" block-color="#ff9900">
					
				</u-slider></view>
			<view class="center" @click="takealbum" >
				
				<u-icon name="photo" size="50" color="#fff"></u-icon>
				
				
			</view>
		</view>
		<canvas id="myCanvas" canvas-id="myCanvas" :style="{
			width: '100vw',
			height: Pageheight+'px'
		}"></canvas>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				animationData: {},
				diyWidth: 180,
				moveX: 0,
				moveY: 0,
				x: 0,
				y: 0,
				value: 1,
				startData: {
					clientX: '',
					clientY: '',
				},
				touch: {},
				coverImageUrl: '',
				pixelRatio: 3,
				Pagewidth: '', //画布对应高度
				Pageheight: '',
				DIYPagewidth: '', //小图片大小
				DIYPageheight: '',
				bgImage: ''
			};
		},
		onLoad(option) { //option为object类型，会序列化上个页面传递的参数
			this.coverImageUrl = option.coverImageUrl
			// this.coverImageUrl = 'https://bianselong01.oss-cn-beijing.aliyuncs.com/cdf86b129ff348b198d333b79d611f35.jpg'
			let _this = this
			uni.getSystemInfo({
				success: res => {
					this.Pageheight = res.windowHeight
					this.Pagewidth = res.windowWidth
					this.moveX = this.Pagewidth / 2 - this.diyWidth / 4
					this.moveY = this.Pageheight / 2 - 50
					this.$nextTick(() => {
						uni.getImageInfo({
							src: _this.coverImageUrl,
							success(image) {
								const query = uni.createSelectorQuery();
								query
									.select(".viewref")
									.boundingClientRect(res2 => {
										_this.DIYPagewidth = res2.width
										_this.DIYPageheight = res2.height
										_this.moveY = _this.Pageheight / 2 - res2.height /
											2
									})
									.exec();
							}
						})
					})
				}
			})

		},
		methods: {
			moveing(){
				this.diyWidth=this.value*10
			},
			endMove(){
				console.log(1)
			},
			//合成图片
			drawProdPicture(eheadImg) {
				let _this = this
				_this.headImg = this.coverImageUrl //去本地缓存获取头像
				uni.getImageInfo({
					src: eheadImg,
					success(image) {
						const canvasId = "myCanvas"
						let ctx = uni.createCanvasContext(canvasId, _this) // 自定义组件中 一定要传this 
						ctx.drawImage(image.path, 0, 0, _this.Pagewidth, _this.Pageheight) // 将头像画到画布上
						ctx.save()

						//生成banner图
						uni.getImageInfo({
							src: _this.headImg, //这里的banner是展示的商品图 
							success(images) {
								let bannerW = _this.DIYPagewidth
								let bannerH = _this.DIYPageheight
								let bannerX = _this.moveX
								let bannerY = _this.moveY

								// 将商品主图画到画布上
								ctx.drawImage(images.path, bannerX, bannerY, bannerW, bannerH)
								ctx.save()
								const imgType = eheadImg.substring(eheadImg.lastIndexOf('.') + 1)
								console.log(666, imgType);
								const fileType = imgType == 'jpg' ? 'jpg' : 'png'
								ctx.draw(false, setTimeout(() => {
									uni.canvasToTempFilePath({
										width: _this.Pagewidth,
										height: _this.Pageheight,
										destWidth: _this.Pagewidth,
										destHeight: _this.Pageheight,
										canvasId,
										fileType,
										quality: 1,
										success: function(res) {
											console.log(666, res.tempFilePath);
											_this.saveImg(res.tempFilePath)
											uni.hideLoading()
										},
										fail(error) {
											console.log('4', error)
											// appEv.arrTips("生成海报失败，请稍后重试！")
											setTimeout(() => {
												uni.hideLoading()
											}, 2000)
										}
									}, _this)
								}, 1000))
							},
							fail(error) {
								console.log('生成商品图失败', error)
								// appEv.arrTips("生成海报失败，获取商品图失败")
								setTimeout(() => {
									uni.hideLoading()
								}, 2000)


							}
						});

					},
					fail(error) {
						console.log('生成头像失败', error)
						// appEv.arrTips("生成海报失败，获取头像失败")
						setTimeout(() => {
							uni.hideLoading()
						}, 2000)
					}
				})
			},

			//下载图片 
			saveImg(filePath) {
				//调用微信内部方法，下载图片
				wx.saveImageToPhotosAlbum({
					filePath,
					success(res) {
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					}
				})
			},


			// 触摸touch事件
			start(e) { //@touchstart 触摸开始

				const query = uni.createSelectorQuery().in(this);
				query
					.select(".viewref")
					.boundingClientRect(res => {
						this.DIYPagewidth = res.width
						this.DIYPageheight = res.height
						this.startData.clientX = e.changedTouches[0].clientX - res.left; //手指按下时的X坐标         
						this.startData.clientY = e.changedTouches[0].clientY - res.top; //手指按下时的Y坐标
					})
					.exec();

			},
			end(e) { //@touchend触摸结束
				// this.moveX = 0;  //触摸事件结束恢复原状
				// this.moveY=0

				if (Math.abs(this.touch.clientX - this.startData.clientX) > 100) { //在事件结束时，判断滑动的距离是否达到出发需要执行事件的要求
					console.log('执行查看跳转事件');
					// this.touch = {};
				} else {
					console.log('滑动距离不够，不执行跳转')
					// this.touch = {};
				}
			},
			move(event) { //@touchmove触摸移动
				let touch = event.touches[0]; //滑动过程中，手指滑动的坐标信息 返回的是Objcet对象
				this.touch = touch;


				let data = touch.clientX - this.startData.clientX;
				let dataY = touch.clientY - this.startData.clientY



				if (this.Pagewidth - data - this.DIYPagewidth < 0) {
					data = this.Pagewidth - this.DIYPagewidth

				}
				if (data < 0) {
					data = 0

				}
				if (dataY < 0) {
					dataY = 0
				}
				if (this.Pageheight - dataY - this.DIYPageheight < 0) {

					dataY = this.Pageheight - this.DIYPageheight
				}

				this.moveX = data;
				this.moveY = dataY;
			},



			cameraError() {


			},



			uploadImgFile(filePath, that) {
				uni.uploadFile({
					url: `${process.uniEnv.baseUrl}/baseVinCode/getVinCodeByImg`,
					filePath: filePath,
					name: 'file',
					formData: {
						file: filePath
					},
					header: {
						'Content-Type': 'multipart/form-data',
					},
					success: response => {
						let res = JSON.parse(response.data.toString("utf8"));
						const {
							data,
							code
						} = res;
						if (code == 200) {
							uni.redirectTo({
								url: `/pages_home/photoIdentification?imageSrc=${filePath}&vinCode=${data}`
							});
						} else {
							uni.showToast({
								title: res.msg,
								duration: 3000
							});
						}
					},

					complete: () => {
						uni.hideLoading()
					}

				});
			},
			//确定
			takePhoto() {
				if (this.bgImage) {
					this.drawProdPicture(this.bgImage)
					return
				}
				const camera = uni.createCameraContext() //创建照相机对象
				camera.takePhoto({ //实现拍照功能
					quality: 'high', //high 高质量成像、 normal 普通质量、row 低质量
					success: (res) => {
						console.log('拍照成功', res)
						this.drawProdPicture(res.tempImagePath)
					}
				})
			},

			takealbum() {
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success: (res) => {
						this.bgImage = res.tempFilePaths[0]
					}
				})
			}

		}

	};
</script>

<style lang="scss">
	.successBtn {
		background-color: #05c160;
		padding: 4rpx 30rpx;
		color: #fff;
		height: 80rpx;
		position: absolute;
		bottom: 50rpx;
		right: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 10rpx;
	}

	.yulan-box {
		position: relative;
		width: 100%;
		height: 100%;
	}

	.tackpic {
		width: 100%;
		height: 100vh;

		.font-title {
			position: fixed;
			background-color: transparent;
			width: 100%;
			height: calc(100vh - 240rpx);
			color: #fff;


			z-index: 89;


		}

		.data-v-1c7472ae {
			width: 100%;
			height: 240rpx;
			background-color: #242424 !important;
			position: relative;
		}
	}

	.pic-bot {
		width: 100%;
		display: flex;
		
		position: absolute;

		top: 80vh;
		z-index: 99;

		.left {
			width: 20%;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.slidercenter {
			width: 60%;
		
			align-items: center;
			justify-content: center;
			
		}

		.center {

			width: 20%;
			display: flex;

		
			align-items: center;
			justify-content: center;


		}


	}
</style>